﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel.Description;
using System.ServiceModel;

namespace WCFMastering.Client
{
    public static class MetadataResolver
    {
        public static IEnumerable<ServiceEndpoint> Resolve(Type contractType, EndpointAddress address)
        {
            return Resolve(contractType, address, MetadataExchangeClientMode.HttpGet);
        }

        public static IEnumerable<ServiceEndpoint> Resolve(Type contractType, EndpointAddress address, MetadataExchangeClientMode mode)
        {
            MetadataExchangeClient client = new MetadataExchangeClient(address.Uri,mode);
            MetadataSet set = client.GetMetadata();
            WsdlImporter importor = new WsdlImporter(set);
            ContractDescription contractDescription = ContractDescription.GetContract(contractType); 
            ServiceEndpointCollection endpointCollection = importor.ImportAllEndpoints();
            return endpointCollection.Where(
                    endPoint =>
                    endPoint.Contract.Name == contractDescription.Name
                    && endPoint.Contract.Namespace == contractDescription.Namespace
                );
        }
    }
}
